﻿using AutoMapper;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WCS_Core_Configuration;
using WCS_Entity.AutoQeuipment;
using WCS_Entity.Dto.AutoEquipmentDto;
using WCS_Entity.User;
using WCS_Repository.Interface;
using WCS_Service.Interface;

namespace WCS_Service.Services
{
    /// <summary>
    /// 自动化设备管理服务
    /// </summary>
    public class AutoEquipmentService : BaseService<AutoEquipmentsEntity>, IAutoEquipmentService
    {
        private readonly IAutoEquipmentRepository _autoEquipmentRepository;
        private readonly IMapper _mapper;
        public AutoEquipmentService(IAutoEquipmentRepository autoEquipmentRepository,
                                    IMapper mapper) 
        {
            _autoEquipmentRepository = autoEquipmentRepository;
            _mapper = mapper;
        }

        #region 自动化设备信息管理
        public async Task<AutoEquipmentDto> CreateAutoEquipmentAsync(CreateAutoEquipmentDto dto)
        {
            AutoEquipmentDto result = new AutoEquipmentDto();
            var flag = await _autoEquipmentRepository.ExistsAsync(a => 
            a.equipmentType == dto.equipmentType && a.equipmentNumber == dto.equipmentNumber);
            if (flag)
            {
                Log.Error($"设备{dto.equipmentNumber}已经添加!");
                return null;
            }
            var entity = _mapper.Map<AutoEquipmentsEntity>(dto);
            entity.createTime = DateTime.Now;

            await _autoEquipmentRepository.InsertAsync(entity);
            result = _mapper.Map<AutoEquipmentDto>(entity);
            return result;
        }
        public async Task<AutoEquipmentDto> UpdateAutoEquipmentAsync(UpdateAutoEquipmentDto dto)
        {
            AutoEquipmentDto result = new AutoEquipmentDto();
            var entity = await _autoEquipmentRepository.QueryByIdAsync(dto.Id);
            if (entity is null)
            {
                Log.Error($"更新设备{dto.Id}没有查询到!");
                return null;
            }
            if (entity.equipmentNumber != dto.equipmentNumber)
            {
                Log.Error($"更新设备{dto.equipmentNumber}的设备编号不一致!");
                return null;
            }
            if (entity.equipmentType != dto.equipmentType)
            { 
                entity.equipmentType = dto.equipmentType;
            }
            if (entity.comType != dto.comType)
            { 
                entity.comType = dto.comType;
            }
            if (entity.protocolType != dto.protocolType)
            {
                entity.protocolType = dto.protocolType;
            }
            if (entity.status != dto.status)
            {
                entity.status = dto.status;
            }
            if (entity.ip != dto.ip)
            {
                entity.ip = dto.ip;
            }
            if (entity.port != dto.port)
            {
                entity.port = dto.port;
            }
            if (entity.MapSite != dto.mapSite)
            { 
                entity.MapSite = dto.mapSite;
            }
            if (entity.AreaCode != dto.areaCode)
            { 
                entity.AreaCode = dto.areaCode;
            }
            if (entity.MapCode != dto.mapCode)
            { 
                entity.MapCode = dto.mapCode;
            }
            if (entity.Extend1 != dto.Extend1)
            {
                entity.Extend1 = dto.Extend1;
            } 
            if (entity.Extend2 != dto.Extend2)
            {
                entity.Extend2 = dto.Extend2;
            } 
            if (entity.Extend3 != dto.Extend3)
            {
                entity.Extend3 = dto.Extend3;
            } 
            if (entity.Extend4 != dto.Extend4)
            {
                entity.Extend4 = dto.Extend4;
            }
            if (entity.Extend5 != dto.Extend5)
            {
                entity.Extend5 = dto.Extend5;
            }
            entity.updataTime = DateTime.Now;

            await _autoEquipmentRepository.UpdateAsync(entity);
            result = _mapper.Map<AutoEquipmentDto>(entity);
            return result;
        }
        public async Task<AutoEquipmentDto> QueryAutoEquipmentAsync(int id)
        {
            AutoEquipmentDto result = new AutoEquipmentDto();
            var entity = await _autoEquipmentRepository.QueryByIdAsync(id);
            if (entity is null)
            {
                Log.Error($"查询设备{id}的信息不存在");
                return null;
            }
            result = _mapper.Map<AutoEquipmentDto>(entity);
            return result;
        }
        public async Task<List<AutoEquipmentDto>> QueryAutoEquipmentBaseTypeAsync(string type)
        {
            List<AutoEquipmentDto> result = new();
            Expression<Func<AutoEquipmentsEntity, bool>> expression = eq => eq.equipmentType == type;
            var entitys = await _autoEquipmentRepository.QueryListByClauseAsync(expression);
            if (entitys is null || !entitys.Any())
            {
                Log.Error($"查询设备类型{type}的信息不存在");
                return null;
            }
            List<Task<AutoEquipmentDto>> addInfos = new();
            foreach (var entity in entitys)
            {
                addInfos.Add(GetDtoInfoAsync(entity));
            }
            await Task.WhenAll(addInfos);
            result = addInfos.Select(e => e.Result).ToList();
            return result;
        }
        public async Task<List<AutoEquipmentDto>> QueryAllAutoEquipmentAsync()
        {
            List<AutoEquipmentDto> result = new List<AutoEquipmentDto>();
            Expression<Func<AutoEquipmentsEntity, object>> orderEx = p => p.createTime;
            var entityInfos = await _autoEquipmentRepository.QueryPageAsync(null, orderEx,OrderByType.Desc,1,10);
            if (entityInfos is null || !entityInfos.Any())
            {
                Log.Error("查询所有设备失败");
                return null;
            }
            List<Task<AutoEquipmentDto>> entityList = new List<Task<AutoEquipmentDto>>();
            foreach (var entityInfo in entityInfos)
            {
                entityList.Add(GetDtoInfoAsync(entityInfo));
            }
            await Task.WhenAll(entityList);
            result = entityList.Select(e => e.Result).ToList();
            return result;
        }
        public async Task<bool> DeleteAutoEquipment(int id)
        {
            return await _autoEquipmentRepository.DeleteByIdAsync(id);
        }
        #endregion

        #region 通信协议配置的基础信息
        public async Task<Dictionary<string, string>> QueryAutoEquipmentTypeAsync()
        {
            var result = await Task.Run(() => 
            {
                var info = AppSettingsConstVars.AutoEquipmentType?.Split(",")?.ToList();
                var dis = AppSettingsConstVars.AutoEquipmentDis?.Split(",")?.ToList();
                if (info is null || dis is null)
                {
                    Log.Error($"系统支持自动化设备查询失败!");
                    return null;
                }
                Dictionary<string, string> infos = new Dictionary<string, string>();
                foreach (var item in info)
                {
                    infos.Add(item, dis[info.IndexOf(item)]);
                }
                return infos;
            });
            return result;
        }
        public async Task<List<string>> QueryAutoEquipmentComTypeAsync()
        {
            var result = await Task.Run(() =>
            {
                var info = AppSettingsConstVars.AutoEquipmentCom?.Split(",")?.ToList();
                if (info is null)
                {
                    return null;
                }
                return info;
            });
            return result;
        }
        #endregion

        #region private
        private async Task<AutoEquipmentDto> GetDtoInfoAsync(AutoEquipmentsEntity entity)
        {
            return await Task.Run(() => _mapper.Map<AutoEquipmentDto>(entity));
        }
        #endregion
    }
}
